package com.dries.security.app.authentication.openid;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/11 14:11
 */
@Component("openIdAuthenticationSecurityConfig")
public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    private AuthenticationSuccessHandler driesAuthSuccessHandler;
    @Resource
    private AuthenticationFailureHandler driesAuthFailureHandler;
    @Resource
    private SocialUserDetailsService userDetailsService;
    @Resource
    private UsersConnectionRepository usersConnectionRepository;
//    @Resource
//    private PersistentTokenRepository persistentTokenRepository;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        // 给自定义短信验证码过滤器初始化
        OpenIdAuthenticationFilter openIdAuthenticationFilter = new OpenIdAuthenticationFilter();
        openIdAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        openIdAuthenticationFilter.setAuthenticationSuccessHandler(driesAuthSuccessHandler);
        openIdAuthenticationFilter.setAuthenticationFailureHandler(driesAuthFailureHandler);
        // smsCodeAuthenticationFilter.setRememberMeServices(new PersistentTokenBasedRememberMeServices(IdUtil.simpleUUID(), userDetailsService, persistentTokenRepository));

        // 给自定义短信Provider初始化
        OpenIdAuthenticationProvider openIdAuthenticationProvider = new OpenIdAuthenticationProvider();
        openIdAuthenticationProvider.setUserDetailsService(userDetailsService);
        openIdAuthenticationProvider.setUsersConnectionRepository(usersConnectionRepository);

        http.authenticationProvider(openIdAuthenticationProvider)
                .addFilterAfter(openIdAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
}
